const user = {
    /***
     * 模块内部的 action、mutation 和 getter 是注册在全局命名空间
     * 通过添加 namespaced: true 的方式使其成为带命名空间的模块
     */
    namespaced: true,
    /** */
    state: {
        loginInfo: JSON.parse(sessionStorage.getItem('loginInfo')) || null,
        userCompany: JSON.parse(sessionStorage.getItem('userCompany')) || null,
    },
    /**mutation 必须是同步函数，this.$store.commit('xxx')触发
     * mapMutations 在组件中可使用mapMutations，将 this.xxx() 映射为 this.$store.commit('xxx')
     */
    mutations: {
        SET_USER: (state, loginInfo) => {
            state.loginInfo = loginInfo;
            if (loginInfo == null) {
                sessionStorage.removeItem('loginInfo');
            } else {
                sessionStorage.setItem('loginInfo', JSON.stringify(loginInfo));
            }
        },
        SET_userCompany: (state, userCompany) => {
            state.userCompany = userCompany;
            if (userCompany == null) {
                sessionStorage.removeItem('userCompany');
            } else {
                sessionStorage.setItem('userCompany', JSON.stringify(userCompany));
            }
        }
    },
    /** actions 可异步, this.$store.dispatch('xxx')触发
     * mapActions 在组件中可使用mapActions，将this.xxx() 映射为this.$store.dispatch('xxx') 
     * */
    actions: {
        cacheLoginer({
            commit
        }, loginInfo) {
            commit('SET_USER', loginInfo);
        },
        removeLoginer({
            commit
        }) {
            commit('SET_USER', null);
        },
        cacheUserCompany({
            commit
        }, userCompany) {
            commit('SET_userCompany', userCompany);
        },
        removeUserCompany({
            commit
        }) {
            commit('SET_userCompany', null);
        },
        removeAll({
            commit
        }) {
            commit('SET_USER', null);
            commit('SET_userCompany', null);
        },
    },
    /**
     * mapGetters 在组件中可使用mapGetters，将this.xxx 映射为 this.$store.getters.xxx
     */
    getters: {
        loginInfo: state => {
            return state.loginInfo
        },
        name: state => {
            if (state.loginInfo) {
                return state.loginInfo.name;
            } else {
                return "";
            }
        },
        role: state => {
            if (state.loginInfo.roles) {
                return state.loginInfo.roles[0].rolename;
            } else {
                return "";
            }
        },
    }
}

export default user